<!-- 设置系统主题颜色 -->
<template>
  <el-tooltip effect="dark" :content="'换肤'" placement="bottom">
    <el-color-picker
      class="theme-picker"
      popper-class="theme-picker-dropdown"
      :predefine="['#409EFF', '#1890ff', '#304156','#212121','#11a983', '#13c2c2', '#6959CD', '#f5222d']"
      v-model="theme"
      @change="themeChange"
    />
  </el-tooltip>
</template>

<script>
// element-ui 在模块中的版本号
const version = require('element-ui/package.json').version;
// 默认主题颜色编码
const ORIGINAL_THEME = '#409EFF';

import { valColorCode } from '@/utils/validate';
import * as cusService from '@/api/services/cus.service';

export default {
  data() {
    return {
      chalk: '', // content of theme-chalk css
      theme: this.$store.state.settings.theme
    }
  },
  created(){
    // 获取-登录用户信息
    this.getLuserInfo();
  },
  methods: {
    /** 获取-登录用户信息 */
    getLuserInfo(){
      const that = this;

      that.$store.dispatch('user/getInfo').then(res => {
        // // 设置-系统侧边栏展开状态
        // if(res.sidbarState == 'false'){
        //   that.$store.dispatch('app/toggleSideBar');
        // }

        // 设置-用户系统主题
        if(res.themeCode && valColorCode(res.themeCode)){
          that.theme = res.themeCode;

          // 获取成功，保存主题颜色
          that.$store.dispatch('settings/changeSetting', {
            key: 'theme',
            value: res.themeCode
          });

          // 显示新的主题颜色
          that.setTheme(res.themeCode);
        }
      });
    },
    /** 切换主题颜色 */
    themeChange(val) {
      const that = this;

      // 服务器保存系统主题设置
      cusService.updSysTheme({themeCode: val}).then(res => {
        if(res.code != 1) {
          that.U.qerror('设置主题失败');
        }else{
          // 保存主题颜色设置至vue缓存
          that.$store.dispatch('settings/changeSetting', {
            key: 'theme',
            value: val
          });

          // 显示新的主题颜色
          that.setTheme(val);
        }
      });
    },
    /**
     * 设置-主题
     * @param val 颜色代码
     */
    async setTheme(val){
      const that = this;

      const oldVal = that.chalk ? that.theme : ORIGINAL_THEME;
      if (typeof val !== 'string') return;

      const themeCluster = that.getThemeCluster(val.replace('#', ''));
      const originalCluster = that.getThemeCluster(oldVal.replace('#', ''));

      const getHandler = (variable, id) => {
        return () => {
          const originalCluster = that.getThemeCluster(ORIGINAL_THEME.replace('#', ''));
          const newStyle = that.updateStyle(that[variable], originalCluster, themeCluster);

          let styleTag = document.getElementById(id);
          if (!styleTag) {
            styleTag = document.createElement('style');
            styleTag.setAttribute('id', id);
            document.head.appendChild(styleTag);
          }
          styleTag.innerText = newStyle;
        }
      };

      if (!that.chalk) {
        const url = `https://unpkg.com/element-ui@${version}/lib/theme-chalk/index.css`;
        await that.getCSSString(url, 'chalk');
      }

      const chalkHandler = getHandler('chalk', 'chalk-style');

      chalkHandler();

      const styles = [].slice.call(document.querySelectorAll('style')).filter(style => {
        const text = style.innerText;
        return new RegExp(oldVal, 'i').test(text) && !/Chalk Variables/.test(text);
      });

      styles.forEach(style => {
        const { innerText } = style;
        if (typeof innerText !== 'string') return;
        style.innerText = that.updateStyle(innerText, originalCluster, themeCluster);
      });
    },
    // 更新样式
    updateStyle(style, oldCluster, newCluster) {
      let newStyle = style;
      oldCluster.forEach((color, index) => {
        newStyle = newStyle.replace(new RegExp(color, 'ig'), newCluster[index]);
      })
      return newStyle;
    },
    // 设置-chalk的值
    getCSSString(url, variable) {
      return new Promise(resolve => {
        const xhr = new XMLHttpRequest();
        xhr.onreadystatechange = () => {
          if (xhr.readyState === 4 && xhr.status === 200) {
            this[variable] = xhr.responseText.replace(/@font-face{[^}]+}/, '');
            resolve();
          }
        }
        xhr.open('GET', url);
        xhr.send();
      });
    },
    // 获取-主题颜色编码
    getThemeCluster(theme) {
      const tintColor = (color, tint) => {
        let red = parseInt(color.slice(0, 2), 16);
        let green = parseInt(color.slice(2, 4), 16);
        let blue = parseInt(color.slice(4, 6), 16);

        if (tint === 0) { // when primary color is in its rgb space
          return [red, green, blue].join(',');
        } else {
          red += Math.round(tint * (255 - red));
          green += Math.round(tint * (255 - green));
          blue += Math.round(tint * (255 - blue));

          red = red.toString(16);
          green = green.toString(16);
          blue = blue.toString(16);

          return `#${red}${green}${blue}`;
        }
      };

      const shadeColor = (color, shade) => {
        let red = parseInt(color.slice(0, 2), 16);
        let green = parseInt(color.slice(2, 4), 16);
        let blue = parseInt(color.slice(4, 6), 16);

        red = Math.round((1 - shade) * red);
        green = Math.round((1 - shade) * green);
        blue = Math.round((1 - shade) * blue);

        red = red.toString(16);
        green = green.toString(16);
        blue = blue.toString(16);

        return `#${red}${green}${blue}`;
      };

      const clusters = [theme];
      for (let i = 0; i <= 9; i++) {
        clusters.push(tintColor(theme, Number((i / 10).toFixed(2))));
      }

      clusters.push(shadeColor(theme, 0.1));

      return clusters;
    },

  }
}
</script>

<style>
.theme-message,
.theme-picker-dropdown {
  z-index: 99999 !important;
}

.theme-picker .el-color-picker__trigger {
  height: 20px !important;
  width: 20px !important;
  border: none !important;
  padding: 0 !important;
  margin-top: 10px;
}

.theme-picker-dropdown .el-color-dropdown__link-btn {
  display: none;
}
</style>
